<template>
  <div class="announcement-container">
    <div class="header">
      <h2>公告栏1</h2>
      <div class="action-buttons">
        <!-- 教师可见的管理按钮 -->
        <el-button
          v-if="authState.role === 'teacher'"
          type="info"
          plain
          @click="showManageDialog = true"
          class="manage-btn"
        >
          <el-icon><Setting /></el-icon> 管理公告
        </el-button>
        <!-- 教师可见的新建按钮 -->
        <el-button
          v-if="authState.role === 'teacher'"
          type="primary"
          @click="showCreateDialog = true"
          class="create-btn"
        >
          <el-icon><Plus /></el-icon> 新建公告
        </el-button>
      </div>
    </div>

    <!-- 公告列表 -->
    <div class="announcement-list" v-if="announcements.length > 0">
      <div
        class="announcement-card"
        :class="{ pinned: item.is_pinned }"
        v-for="item in announcements"
        :key="item.id"
      >
        <div class="announcement-title">
          <span v-if="item.is_pinned" class="pinned-tag">置顶</span>
          {{ item.title }}
        </div>
        <div class="announcement-meta">
          <span class="meta-item">
            <el-icon><User /></el-icon>
            {{ item.created_by || '系统管理员' }}
          </span>
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            {{ formatDateTime(item.created_at) }}
          </span>
        </div>
        <div class="announcement-body">
          {{ item.content }}
        </div>
      </div>
    </div>
    <el-empty v-else description="暂无公告" />

    <!-- 新建公告对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新建公告"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入公告内容"
          />
        </el-form-item>

        <el-form-item label="置顶">
          <el-switch v-model="formData.is_pinned" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">发布公告</el-button>
      </template>
    </el-dialog>

    <!-- 管理公告对话框 -->
    <el-dialog
      v-model="showManageDialog"
      title="公告管理"
      width="750px"
      :close-on-click-modal="false"
      @closed="fetchAnnouncements"
    >
      <el-table
        :data="announcements"
        style="width: 100%"
        height="400px"
        stripe
        border
      >
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column label="创建人" width="120">
          <template #default="{ row }">
            {{ row.created_by || '系统管理员' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.is_pinned" type="danger" size="small">置顶</el-tag>
            <el-tag v-else type="info" size="small">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row.id)"
              :loading="deletingId === row.id"
              plain
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { Plus, Setting, User, Clock } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { authState } from '../simpleStore.js'

// 公告列表
const announcements = ref([])
const showCreateDialog = ref(false)
const showManageDialog = ref(false)
const deletingId = ref(null)

// 表单数据
const formData = reactive({
  title: '',
  content: '',
  is_pinned: false
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { max: 500, message: '内容长度不能超过500个字符', trigger: 'blur' }
  ]
}

const formRef = ref(null)

// 格式化日期时间
const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 获取公告列表
const fetchAnnouncements = async () => {
  try {
    const res = await axios.get('/api/public-announcements/')
    announcements.value = res.data
  } catch (error) {
    ElMessage.error('获取公告失败：' + error.message)
  }
}

onMounted(fetchAnnouncements)

// 处理新建公告提交
const handleSubmit = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return false
  })

  try {
    const payload = {
      title: formData.title,
      content: formData.content,
      is_pinned: formData.is_pinned
    }
    
    const response = await axios.post(
      '/api/teacher/announcements/',
      payload,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.status === 201) {
      ElMessage.success('公告发布成功')
      showCreateDialog.value = false
      await fetchAnnouncements()
      formData.title = ''
      formData.content = ''
      formData.is_pinned = false
    }
  } catch (error) {
    console.error('创建公告失败', error.response?.data)
    ElMessage.error('发布失败：' + (error.response?.data?.detail || '请检查网络'))
  }
}

// 处理删除公告
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条公告吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    deletingId.value = id
    const response = await axios.delete(`/api/teacher/announcements/${id}/`)
    
    if (response.status === 204) {
      ElMessage.success('公告删除成功')
      await fetchAnnouncements()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.response?.data?.detail || '请检查网络'))
    }
  } finally {
    deletingId.value = null
  }
}
</script>

<style scoped>
.announcement-container {
  max-width: 800px;
  margin: 30px auto;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.create-btn {
  min-width: 110px;
  height: 36px;
}

.manage-btn {
  min-width: 110px;
  height: 36px;
}

.announcement-list {
  max-height: calc(100vh - 220px);
  overflow-y: auto;
  padding-right: 8px;
}

.announcement-card {
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.announcement-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.announcement-card.pinned {
  border-left: 3px solid #f56c6c;
  background-color: #fff9f9;
}

.announcement-title {
  font-weight: 600;
  font-size: 1.1rem;
  margin-bottom: 8px;
  color: #333;
  display: flex;
  align-items: center;
}

.pinned-tag {
  display: inline-block;
  padding: 2px 6px;
  margin-right: 8px;
  font-size: 0.75rem;
  color: #fff;
  background-color: #f56c6c;
  border-radius: 4px;
}

.announcement-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 0.85rem;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.announcement-body {
  font-size: 0.95rem;
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

:deep(.el-dialog__title) {
  font-size: 1.1rem;
  font-weight: 500;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #f0f0f0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .announcement-container {
    margin: 15px;
    padding: 15px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  :deep(.el-dialog) {
    width: 90% !important;
  }
}
</style>